<?php

namespace Crm\Controller;

/**
 * 系统扩展字段控制器
 *
 * @author Alen
 * @since 1.0 <2014-11-11> by sutroon, 
 * @since 2.0 <2014-12-12> by sutroon
 */
class ExfieldController extends AppbaseController {

    private $targets = array('CUSTOMER', 'PRODUCT');

    public function index() {
        $target = I('target');
        if (!in_array($target, $this->targets)) {
            die('参数不合法!');
        }
        if (!$this->user_login_data['is_superadmin']) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $where['target'] = $target;
        $list = D('CommonExfield')->get_paging_list();
        $this->assign('list', set_siteID_text($list));
        $this->assign('page', $page);
        $this->assign('target', $target);
        $this->display_tpp();
    }

    // 新增 2014-12-12 by sutroon
    public function item_add() {
        $target = I('target');
        if (!$target) {
            $this->act_close_dialog(false, '参数有误!');
        }
        if (!in_array($target, $this->targets)) {
            $this->act_close_dialog(false, '参数不合法!');
        }
        $this->assign('siteID', $this->loginData['siteID']);
        $this->assign('target', $target);
        $this->display();
    }

    // 编辑 2014-11-11 by sutroon
    public function item_edit() {
        $id = I('id');
        if (!$id) {
            $this->act_close_dialog(false, '参数有误!');
        }
        $data = M($this->table)->find($id);
        if (!$data) {
            $this->act_close_dialog(false, '记录不存在!');
        }
        $this->assign('data', $data);
        $this->display();
    }

    // 保存新增的数据 2014-12-12 by sutroon
    public function item_add_save() {
        $target = I('target');
        $siteID = I('siteID');
        $field = trim(I('field'));
        $type = I('type');
        $inputType = I('inputType');
        $length = I('length');
        $params = create_params();
        $params->addParam('siteID', 'require', '租户ID无效');
        $params->addParam('label', 'require', '属性名称未填写!');
        if (!$field) {
            $params->addError('英文名称未填写!');
        }
        $params->addData('field', $field);
        $params->addParam('type', 'require', '数据类型未填写!');
        $params->addParam('target', 'require', '模块名称无效!');
        switch ($type) {
            case 'varchar':
                // $params->addParam('length', 'number', '字段长度未填写!');
                $length = 255;
                $params->addData('length', $length);
                break;
            case 'decimal':
                // $params->addParam('length', 'number', '精度未填写!');
                $length = 2;
                $params->addData('length', $length);
                break;
        }
        $params->addParam('inputType', 'require', '组件类型未选择!');
        if ($inputType == 'select' || $inputType == 'radio' || $inputType == 'checkbox') {
            $params->addParam('optionalValue', 'require', '可选值未填写!');
        }
        $params->addParam('ordinal', 'number', '排序未填写!');

        if ($params->hasError()) {
            $this->act_error($params->getError());
        }

        if (!in_array($target, $this->targets)) {
            $this->act_error('参数不合法!');
        }

        $M = M($this->table);
        if ($M->where("`field`='$field' and target='$target' and siteID=$siteID")->count() > 0) {
            $this->act_error("英文名称[$field]已存在!");
        }

        $table = false;
        switch ($target) {
            case 'CUSTOMER':
                $table = 'tcustomer_ex_' . $siteID;
                break;
            case 'PRODUCT':
                $table = 'tproduct_ex_' . $siteID;
                break;
        }
        if (!$M->query("show tables like '$table'")) {
            $sql = "create table if not exists $table (userID int not null primary key comment '用户表主键编号') comment '客户属性扩展表 1.0 2014-11-11 by sutroon' ENGINE=InnoDB default CHARSET=utf8;";
            $result = $M->query($sql);
            if (false === $result) {
                $this->act_error($M->getDbError());
            }
        }

        $params->addData('default');
        $params->addData('comment');
        $params->addData('isDisplay');
        $params->addData('isRequire');
        $params->addData('allowSearch');

        $isRequire = I('isRequire');
        $default = I('default');
        if ($isRequire == '1') {
            $rule = 'require';
            switch ($type) {
                case 'int':
                case 'smallint':
                    $rule = 'number';
                    break;
                case 'decimal':
                    $rule = 'double';
                    break;
            }
            $params->addData('rule', $rule);
        }
        $params->addData('null', $isRequire == '1' ? 'NO' : 'YES');
        $result = $M->add($params->getParams());
        if (false === $result) {
            $this->act_close_dialog(false, '新增数据保存失败!');
        }
        switch ($type) {
            case 'varchar':
                $type .= "($length)";
                break;
            case 'decimal':
                $type .= "(12,$length)";
                break;
        }
        $isRequire = $isRequire == '1' ? 'NOT NULL' : '';
        $default = $default ? "DEFAULT '$default'" : '';
        $comment = $comment ? "COMMENT '$comment'" : '';
        $sql = trim("alter table $table add $field $type $isRequire $default $comment");
        $result = $M->execute($sql);
        BaseAction::add_user_event_log('扩展字段', "[新增%] $user=$siteID, target=$target label=$label, field=$field, type=$type", $result);
        $this->act_close_dialog($result, '保存%!');
    }

    // 保存编辑的数据 2014-11-11 by sutroon
    public function item_edit_save() {
        $target = I('target');
        $siteID = I('siteID');
        $inputType = I('inputType');
        $params = create_params();
        $params->addParam('id', 'require', '编号无效');
        $params->addParam('siteID', 'require', '租户ID无效');
        $params->addParam('label', 'require', '属性名称未填写!');
        $params->addParam('inputType', 'require', '组件类型未选择!');
        if ($inputType == 'select' || $inputType == 'radio' || $inputType == 'checkbox') {
            $params->addParam('optionalValue', 'require', '可选值未填写!');
        }
        $params->addParam('ordinal', 'number', '排序未填写!');

        if ($params->hasError()) {
            $this->act_error($params->getError());
        }

        if (!in_array($target, $this->targets)) {
            $this->act_error('参数不合法!');
        }

        $M = M($this->table);

        $params->addData('default');
        $params->addData('isDisplay');
        $params->addData('isRequire');
        $params->addData('allowSearch');
        $params->addData('updatedTime', now());

        $result = $M->save($params->getParams());
        BaseAction::add_user_event_log('扩展字段', "[编辑%] $user=$siteID, target=$target, $id=" . I('id') . ", field=" . I('field') . ", label=" . I('label') . ", inputType=$inputType", $result);
        $this->act_close_dialog($result, '保存%!');
    }

    // 批量操作：隐藏/显示,必填/可选 2014-11-11 by sutroon
    public function batch_opt_save() {
        $target = I('target');
        $siteID = $this->loginData['siteID'];
        $v = I('v');
        switch ($v) {
            case 'show':
            case 'hide':
                $field = 'isDisplay';
                $val = $v == 'show' ? '1' : '0';
                break;
            case 'require':
            case 'optional':
                $field = 'isRequire';
                $v = $v == 'require' ? '1' : '0';
                break;
        }

        $result = M($this->table)->where("target='$target' and sysLevel>0 and siteID=$siteID")->setField($field, $v);
    }

    // 检测字段是否存在 2014-11-11 by sutroon
    public function check_field() {
        $siteID = $this->loginData['siteID'];
        $field = I('field');
        $target = I('target');
        $list = M($this->table)->where("field='$field' and siteID=$siteID and target='$target'")->getField('id,type');
        $this->ajaxReturn(is_null($list) ? array('result' => false) : array('result' => true, 'msg' => current($list), 'id' => key($list)));
    }

    // 字段排序提升 2014-11-11 by sutroon
    public function item_up() {
        $id = I('id');
        $target = I('target');
        $siteID = $this->loginData['siteID'];
        $this->move_row_up_or_down($this->table, $id, 'up', "target='$target' and sysLevel>0 and siteID=$siteID");
        $this->ajaxReturn(array('result' => true));
    }

    // 字段排序下降 2014-11-11 by sutroon
    public function item_down() {
        $id = I('id');
        $target = I('target');
        $siteID = $this->loginData['siteID'];
        $this->move_row_up_or_down($this->table, $id, 'down', "target='$target' and sysLevel>0 and siteID=$siteID" . $siteID);
        $this->ajaxReturn(array('result' => true));
    }

    // 上下移动行次序  2014-11-11 by sutroon
    function move_row_up_or_down($table, $id, $flag = 'up', $where_static = '') {
        $M = M($table);
        $exp = $flag == 'up' ? '<' : '>';
        $ordinal = $M->where('id=' . $id)->getField('ordinal');
        if ($where_static) {
            $where_static = ' and ' . $where_static;
        }
        $list2 = $M->where("ordinal $exp $ordinal $where_static")->getField('id, ordinal');
        if (is_null($list2)) {
            return 'End';
        }
        $M->where('id=' . $id)->setField('ordinal', current($list2));
        $result = $M->where('id=' . key($list2))->setField('ordinal', $ordinal);
        return $result;
    }

    public function test() {
        $siteID = $this->loginData['siteID'];
        $list = array(
            array('field' => 'qq', 'type' => 'varchar', 'length' => '32', 'default' > '', 'comment' => '腾讯QQ号码', 'label' => 'QQ', 'inputType' => 'text', 'optionalValue' => '', 'isRequire' => 1, 'rule' => 'require', 'siteID' => $siteID),
            array('field' => 'skype', 'type' => 'varchar', 'length' => '32', 'default' > '', 'comment' => '微软Skype帐号', 'label' => 'Skype', 'inputType' => 'text', 'optionalValue' => '', 'isRequire' => 0, 'rule' => 'require', 'siteID' => $siteID),
            array('field' => 'email', 'type' => 'varchar', 'length' => '32', 'default' > '', 'comment' => '电子邮件', 'label' => '邮件', 'inputType' => 'text', 'optionalValue' => '', 'isRequire' => 0, 'rule' => 'require', 'siteID' => $siteID),
            array('field' => 'group', 'type' => 'varchar', 'length' => '16', 'default' > '', 'comment' => '客户群组(A,B,C,D,E)', 'label' => '客户群组', 'inputType' => 'select', 'optionalValue' => 'A,B,C,D,E', 'isRequire' => 1, 'rule' => 'require', 'siteID' => $siteID),
            array('field' => 'source', 'type' => 'varchar', 'length' => '16', 'default' > '电话', 'comment' => '客户来源(电话,QQ,微信,广告,网站,其他)', 'label' => '客户来源', 'inputType' => 'select', 'optionalValue' => '电话,QQ,微信,广告,网站,其他', 'isRequire' => 1, 'rule' => 'require', 'siteID' => $siteID),
        );
        foreach ($list as $row) {
            
        }
    }

    public function assert_upr($rule = '') {
        
    }

}
